<template>
  <div>
    <!--  面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!--      添加按钮-->
      <el-row>
        <el-col>
          <el-button type="primary" plain @click="addRoleVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!--  列表区域-->
      <el-table :data="roleList" border stripe>
        <!--        展开符-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bd-bottom',i1 === 0 ? 'bd-top':'','center']" v-for="(item1,i1) in scope.row.children"
                    :key="item1.id">
              <!--  一级权限-->
              <el-col :span="5">
                <el-tag closable @close="deleteRole(scope.row,item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--  二级权限-->
              <el-col :span="19">
                <el-row :class="[i2 === 0 ? '':'bd-top','center']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="deleteRole(scope.row,item2.id)">
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!--    三级权限-->
                  <el-col :span="18">
                    <el-tag type="warning" closable v-for="(item3,i3) in item2.children" :key="item3.id"
                            @close="deleteRole(scope.row,item3.id)">
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!--        列表-->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit"
                       @click="showEditRole(scope.row.id)">编辑
            </el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleRuleId(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRolePrivileges(scope.row)">分配角色
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--    添加角色-->
    <el-dialog title="添加角色" :visible.sync="addRoleVisible" width="50%" @close="closeForm">
      <!--      添加角色表单区域-->
      <el-form :model="addRole" ref="addRuleRef" label-width="70px">
        <el-form-item label="角色id" prop="roleId">
          <el-input v-model="addRole.roleId"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRole.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!--      底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRule">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户-->
    <el-dialog title="修改角色" :visible.sync="updataRuleVisible" width="50%" @close="updataRuleClose">
      <el-form :model="updataFrom" ref="updataFormRef" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="updataFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="updataFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="updataRuleVisible = false">取 消</el-button>
    <el-button type="primary" @click="updataRuleInfo">确 定</el-button>
  </span>
    </el-dialog>
    <!--    分配角色对话框-->
    <el-dialog title="分配权限" :visible.sync="setRolePrivileges" width="50%" @close="setCloseDialog">
      <!--     树形控件-->
      <el-tree :data="roleNumber" :props="treeRoleProps" show-checkbox node-key="id"
               :default-expand-all="true" :default-checked-keys="defkeys" ref="treeRef">
      </el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRolePrivileges = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],    //角色列表
      addRole: {       //添加角色
        roleName: '',
        roleDesc: '',
        roleId: ''
      },
      addRoleVisible: false,   //控制按钮
      updataRuleVisible: false, //修改用户框
      updataFrom: {},         //储存查到的用户信息
      setRolePrivileges: false,  //分配角色按钮显示隐藏
      roleNumber: {},         //权限数据
      //树形控图
      treeRoleProps: {
        label: 'authName',     //要显示的数据名
        children: 'children'    //子代的数据名
      },
      defkeys: [],       //收集三级权限列表
      roleID: '',        //即将分配角色的id

    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const {data: res} = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.roleList = res.data
      // console.log(this.roleList)

    },
    //监听 对话框改变  重置信息
    closeForm() {
      this.$refs.addRuleRef.resetFields()
    },
    //添加角色  预验证
    addRule() {
      this.$refs.addRuleRef.validate(async valid => {
        // console.log(valid)
        const {data: res} = await this.$http.post('roles', this.addRole)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败！')
        }
        this.$message.success('添加用户成功！')
        this.addRoleVisible = false
        this.getRolesList()
      })
    },
    //删除用户
    async deleRuleId(id) {
      // console.log(id)
      const confirmRef = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        center: true,
        type: 'warning',
      }).catch(err => err)
      //确认删除 返回 confirm   取消删除 返回cancel
      if (confirmRef !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const {data: res} = await this.$http.delete('roles/' + id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败！')
      }
      this.$message.success('删除角色成功！')
      this.getRolesList()
    },
    //监听 对话框改变  重置信息
    updataRuleClose() {
      this.$refs.updataFormRef.resetFields()
    },
    //根据 ID 查询角色
    async showEditRole(id) {
      const {data: res} = await this.$http.get('roles/' + id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色数据失败')
      }
      this.updataFrom = res.data
      // console.log(res.data)
      this.updataRuleVisible = !this.updataRuleVisible
    },
    // 修改用户
    updataRuleInfo() {
      this.$refs.updataFormRef.validate(async valid => {
        if (!valid) return
        const {data: res} = await this.$http.put('roles/' + this.updataFrom.roleId, {
          roleName: this.updataFrom.roleName,
          roleDesc: this.updataFrom.roleDesc
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改用户信息失败！')
        }
        this.updataRuleVisible = false
        this.getRolesList()
        this.$message.success('修改用户信息成功！')
      })
    },
    //删除角色权限
    async deleteRole(role, rightId) {
      const confirmRusult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRusult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      // console.log(success)
      const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      //重新赋值 刷新展开框权限列表
      role.children = res.data

    },
    //展示对话框权限列表
    async showSetRolePrivileges(role) {
      //储存权限id
      this.roleID = role.id
      // console.log(role.id)
      const {data: res} = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        this.$message.error('获取权限数据失败！')
      }
      this.roleNumber = res.data
      // console.log(this.roleNumber)


      this.getDefKeys(role, this.defkeys)

      this.setRolePrivileges = true
    },
    //递归将三级权限列表传入defkeys中
    getDefKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getDefKeys(item, arr))
    },
    // 监听分配权限的关闭
    setCloseDialog() {
      this.defkeys = []
    },
    //点击为角色分配权限
    async allotRights() {
      const key = [
        //全选
        ...this.$refs.treeRef.getCheckedKeys(),
        //半选
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // console.log(key)

      const idStr = key.join(',')
      const {data: res} = await this.$http.post(`roles/${this.roleID}/rights`, {rids: idStr})
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限错误！')
      }
      this.$message.success('分配权限成功！')
      this.getRolesList()
      this.setRolePrivileges = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 8px;
}

.bd-top {
  border-top: 1px solid #eee;
}

.bd-bottom {
  border-bottom: 1px solid #eee;
}

.center {
  display: flex;
  align-items: center;
}
</style>
